import { Injectable, OnApplicationBootstrap } from '@nestjs/common'
import { BrowserWindow, Menu, app, shell, globalShortcut } from 'electron'
import { resolve } from 'path'
import { electronApp, optimizer } from '@electron-toolkit/utils'
import icon from '../../../resources/icon.png?asset'
import { is } from '@electron-toolkit/utils'
import { LogService } from '@main/services/log.service'
import log from 'electron-log'
import template from '@main/menus/index'
import { appInfo } from '@shared/constant/system'

@Injectable()
export class ElectronApp implements OnApplicationBootstrap {
  private mainWindow: BrowserWindow | null = null
  private isQuitting = false

  constructor(private readonly logService: LogService) {}

  async onApplicationBootstrap() {
    try {
      await app.whenReady()

      // 设置应用 ID
      electronApp.setAppUserModelId('com.electron')

      // 创建窗口
      this.createWindow()

      // 构建菜单
      const menu = Menu.buildFromTemplate(template)
      Menu.setApplicationMenu(menu)

      // 开发环境快捷键支持
      app.on('browser-window-created', (_, window) => {
        optimizer.watchWindowShortcuts(window)
      })

      // macOS 激活事件
      app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) this.createWindow()
      })

      // 关闭所有窗口时退出（macOS 除外）
      app.on('window-all-closed', () => {
        if (process.platform !== 'darwin') app.quit()
      })

      // 退出前清理
      app.on('before-quit', async (event) => {
        if (this.isQuitting) return
        this.logService.info('正在执行退出前清理...')
        event.preventDefault()
        this.isQuitting = true
        app.quit()
      })
    } catch (error) {
      log.error('[App] 启动失败:', error)
      app.quit()
    }
  }

  private createWindow(): void {
    if (this.mainWindow) return

    const PRELOAD_PATH = resolve(__dirname, '../preload/index.js')
    this.mainWindow = new BrowserWindow({
      width: 1080,
      height: 670,
      show: false,
      autoHideMenuBar: true,
      title: appInfo.name,
      icon: process.platform === 'linux' ? icon : undefined,
      webPreferences: {
        preload: PRELOAD_PATH,
        sandbox: false,
        contextIsolation: true,
        devTools: true
      }
    })

    this.mainWindow.on('ready-to-show', () => {
      this.mainWindow?.show()
      this.mainWindow?.webContents.executeJavaScript(
        `document.title = ${JSON.stringify(appInfo.name)}`
      )
    })

    this.mainWindow.webContents.setWindowOpenHandler((details) => {
      shell.openExternal(details.url)
      return { action: 'deny' }
    })
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
      this.mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
    } else {
      this.mainWindow.loadFile(resolve(__dirname, '../renderer/index.html'))
    }

    if (is.dev) {
      this.mainWindow.webContents.openDevTools({ mode: 'detach' })
    }
    this.setupGlobalShortcuts()
  }

  private setupGlobalShortcuts(): void {
    // 防止重复注册
    globalShortcut.unregisterAll()

    const win = this.mainWindow
    if (!win || win.isDestroyed()) return

    // 打开/关闭 DevTools
    globalShortcut.register('CommandOrControl+Shift+I', () => {
      win.webContents.toggleDevTools()
    })

    // 强制刷新（忽略缓存）
    globalShortcut.register('CommandOrControl+R', () => {
      win.webContents.reloadIgnoringCache()
    })

    // 可选：支持 F5 刷新（含缓存）
    globalShortcut.register('F5', () => {
      win.webContents.reload()
    })

    // 可选：支持 Ctrl+F5 / Shift+F5 忽略缓存刷新
    globalShortcut.register('CommandOrControl+Shift+R', () => {
      win.webContents.reloadIgnoringCache()
    })

    this.logService.info('已注册全局调试快捷键: Ctrl+Shift+I, Ctrl+R, F5 等')
  }
}
